<template>
  <div class="app-container">
    <FilterSearch :value="queryParams" :config="configData" :labelCol="8" :wrapperCol="16" layout="inline">
    </FilterSearch>
    <div class="main">
      <div class="table">
        <a-table :scroll="{ x: 1500 }" bordered :dataSource="tableData.dataSource" :columns="tableData.columns"
          :loading="tableData.loading">
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="handleChange(record, 'details')">
                详情
              </a-button>
            </template>
            <template v-if="column.key === 'index'">
              <span>
                {{ (index + 1) }}
              </span>
            </template>
            <template v-if="column.key === 'materialType'">
              <template v-for="item in typeOptions.options1">
                <span v-if="record.materialType == item.codeValue" color="#f50">{{ item.codeName }}</span>
              </template>
            </template>
            <template v-if="column.key === 'state'">
              <template v-for="item in typeOptions.options2">
                <span v-if="record.state == item.codeValue" color="#f50">{{ item.codeName }}</span>
              </template>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal v-model:open="modalOpen.open" style="width: 75%;" title="材料详情" :maskClosable="false" :closable="false">
      <div class="modal-body">
        <a-form :model="formState" disabled ref="formRef" :rules="rules" :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }" autocomplete="off">
          <a-row>
            <a-col :span="8">
              <a-form-item label="材料类型" name="materialType" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-select allowClear v-model:value="formState.materialType" :disabled="modalOpen.status == 1">
                  <a-select-option v-for="(item, index) in typeOptions.options1" :value="item.codeValue"
                    :key="item.codeValue">
                    {{ item.codeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formState.materialType == MATERIAL.REGISTRATION">
            <a-col :span="24">
              <a-form-item label="上传图片材料" name="fileList" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
                <a-upload v-model:file-list="formState.fileList" @change="uploadChange" :action="getHttps"
                  :headers="getHeaders" :before-upload="beforeUpload" list-type="picture-card" @preview="onPreview">
                  <div v-if="formState.fileList.length < 8">
                    <plus-outlined />
                    <div style="margin-top: 8px">上传图片材料</div>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>
          </a-row>
          <a-col :span="8">
            <a-form-item label="合同号" name="contractNum">
              <a-input v-model:value="formState.contractNum" />
            </a-form-item>
          </a-col>
          <a-row v-show="formState.materialType == MATERIAL.REGISTRATION">
            <a-col :span="8" v-for="(item, index) in formState.carNumList" :key="index">
              <a-form-item :label="'车架号'" name="carNum">
                <a-input v-model:value="item.frameNumber" @change="carNumChange">
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="1"></a-col>
            <a-col :span="7">
            </a-col>
          </a-row>
          <a-row v-show="formState.materialType == MATERIAL.REGISTRATION">
            <a-col :span="8">
              <a-form-item label="盒号" name="caseNum">
                <a-input v-model:value="formState.caseNum" disabled>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="件号" name="partNum">
                <a-input v-model:value="formState.partNum" placeholder="自动生成" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="排序号" name="orderNum">
                <a-input v-model:value="formState.orderNum" placeholder="自动生成" disabled />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="formState.materialType == MATERIAL.CONTRACT">
            <a-col :span="8" v-for="(item, index) in contractList" :key="index">
              <a-form-item :label="item.label" :name="item.name" :label-col="{ span: 14 }" :wrapper-col="{ span: 10 }">
                <a-input v-model:value="item.value" @input="item.value = item.value.replace(/[^0-9]/g, '')">
                  <template #addonAfter>
                    份
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8" v-for="(item, index) in formState.reserve1" :key="index">
              <a-form-item :label="item.label" :name="item.name" :label-col="{ span: 14 }" :wrapper-col="{ span: 10 }">
                <a-input v-model:value="item.value" @input="item.value = item.value.replace(/[^0-9]/g, '')">
                  <template #addonAfter>
                    份
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <template #footer>
        <div class="modal-btns">
          <div class="modal-btn">
            <a-button @click="cancel('details')">关闭</a-button>
          </div>
        </div>
      </template>
    </a-modal>

    <div class="shade" v-show="spin">
      <a-spin size="large" />
    </div>
  </div>
</template>
<script  lang='ts' setup>
import { computed, ref, reactive } from 'vue';
import { useRouter } from "vue-router";
import { getMaterialList, materialInfo } from "@/api/commerExpress";
import { getQueryAll, previewFiles } from "@/api/common";
import { getUserInfo } from '@/api/login';
import { user as useUser } from "@/store";
import { MATERIAL } from "@/utils/config";

const user = useUser();
const router = useRouter();

const spin = ref(false);
const queryParams = ref({
  pageNumber: 1,
  pageSize: 10,
  expressNum: "",
  signTime: "",
  signer: ""
});
const contractList = ref([
  {
    label: "售后回租赁合同",
    value: null,
    status: false,
    props: 'afterSalesLeasebakContract'
  },
  {
    label: "抵押合同(盖章)",
    value: null,
    status: false,
    props: 'sealOfMortgageContract'
  },
  {
    label: "款项用途确认函",
    value: null,
    status: false,
    props: 'confirmationLetterForThePurposeOfFunds'
  },
  {
    label: "抵押合同(签字)",
    value: null,
    status: false,
    props: 'signatureOfMortgageContract'
  },
  {
    label: "个人信息保护政策",
    value: null,
    status: false,
    props: 'personalInformationProtectionPolicy'
  },
  {
    label: "挂靠协议",
    value: null,
    status: false,
    props: 'affiliationAgreement'
  },
  {
    label: "租赁物接收确认函及资金收据",
    value: null,
    status: false,
    props: 'leaseReceiptConfirmationAndFundReceipt'
  },
  {
    label: "付款通知书",
    value: null,
    status: false,
    props: 'paymentAdvice'
  },
  {
    label: "服务费确认函",
    value: null,
    status: false,
    props: 'serviceChargeConfirmationLetter'
  },
  {
    label: "款项代收确认函",
    value: null,
    status: false,
    props: 'paymentCollectionConfirmationLetter'
  },
  {
    label: "不可撤销确认函",
    value: null,
    status: false,
    props: 'lrrevocableConfirmationLetter'
  },
  {
    label: "业务确认函",
    value: null,
    status: false,
    props: 'businessConfirmationLetter'
  }
]);
const typeOptions = reactive({
  options1: [],
  options2: []
});
const tableData = reactive({
  dataSource: [],
  columns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      align: 'center'
    },
    {
      title: '合同号',
      dataIndex: 'contractNum',
      key: 'contractNum',
    },
    {
      title: '车架号',
      dataIndex: 'carNum',
      key: 'carNum'
    },
    {
      title: '承租人',
      dataIndex: 'lesseeName',
      key: 'lesseeName'
    },
    {
      title: '材料类型',
      dataIndex: 'materialType',
      key: 'materialType'
    },
    {
      title: '档案状态',
      dataIndex: 'state',
      key: 'state',
    },
    {
      title: '盒号',
      dataIndex: 'caseNum',
      key: 'caseNum',
    },
    {
      title: '件号',
      dataIndex: 'partNum',
      key: 'partNum',
    },
    {
      title: '排序号',
      dataIndex: 'orderNum',
      key: 'orderNum'
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right'
    },
  ],
  total: 0,
  loading: false
});
interface FormState {
  [props: string]: string | number | Array<object>;
}
let formState: FormState = reactive({
  materialType: MATERIAL.REGISTRATION,
  fileList: []
});
const modalOpen = reactive({
  open: false
});
const configData = computed(() => {
  let config = {
    itemConfig: [
      {
        type: "input",
        prop: "expressNum",
        allowClear: "关闭",
        label: "快递单号",
        placeholder: "",
        disabled: true
      },
      {
        type: "input",
        prop: "signer",
        allowClear: "关闭",
        label: "签收人",
        placeholder: "",
        disabled: true
      },
      {
        type: "input",
        prop: "signTime",
        allowClear: "关闭",
        label: "签收日期",
        placeholder: "",
        disabled: true
      }
    ],
    operate: [],
    rules: {

    },
  };
  return config;
});
function handleChange(row: any = {}, type: string) {
  switch (type) {
    case 'details':
      spin.value = true;
      materialInfo({ id: row.id, materialType: row.materialType }).then(async (res: any) => {
        if (res) {
          formState = Object.assign(formState, res);
          for (const key in contractList.value) {
            contractList.value[key]['value'] = res[contractList.value[key]['props']];
          }
          formState['reserve1'] = res['reserve1'] ? JSON.parse(res['reserve1']) : '';
          if (formState.registrationCertificatePhoto) {
            let ids = formState.registrationCertificatePhoto.split(",");
            let fileList = [] as Array<object>;
            for (const key in ids) {
              await previewFiles({ resourceId: ids[key] }).then((res: any) => {
                if (res) {
                  fileList.push({
                    uid: res,
                    name: res,
                    url: res,
                    status: 'done',
                    preview: res,
                    thumbUrl: res,
                    response: {
                      data: ids[key],
                      status: {
                        code: 0,
                        msg: "Success"
                      }
                    }
                  });
                }
              })
            }
            formState['fileList'] = fileList;
          }
          if (formState.carNum) {
            formState.carNumList = [{ frameNumber: formState.carNum }];
          }
          modalOpen.open = true;
          spin.value = false;
        }
      })
      break;
    default:
      break;
  }
}
function cancel(type: string) {
  switch (type) {
    case "details":
      modalOpen.open = false;
      for (const key in formState) {
        delete formState[key];
      }
      formState['fileList'] = [];
      formState['materialType'] = MATERIAL.REGISTRATION;
      break;
    default:
      break;
  }
}
function getLoad() {
  if (Object.keys(user.$state.orderInfo).length <= 0) {
    router.push('/commerexpress');
    return false;
  }
  tableData.loading = true;
  getMaterialList({ expressManageId: user.$state.orderInfo.id }).then(async (res: any) => {
    tableData.dataSource = res;
    tableData.total = res.length;
    tableData.loading = false;
    queryParams.value = {
      ...user.$state.orderInfo,
      expressManageId: user.$state.orderInfo.id,
      signer: await getUserInfo({ createGlobalUserId: user.$state.orderInfo.signer })
    }
  })
}
function getOptionsList() {
  getQueryAll({ codeType: 'materialType' }).then((res: any) => {
    typeOptions.options1 = res;
  });
  getQueryAll({ codeType: 'state' }).then((res: any) => {
    typeOptions.options2 = res;
  });
}
getLoad();
getOptionsList();
</script>
<style></style>